package io.grpc.examples.helloworldtls;

import java.io.File;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.SSLException;

import io.grpc.ManagedChannel;
import io.grpc.StatusRuntimeException;
import io.grpc.examples.helloworld.GreeterGrpc;
import io.grpc.examples.helloworld.HelloReply;
import io.grpc.examples.helloworld.HelloRequest;
import io.grpc.examples.helloworldtls.trust.MyTrustManagerFactory;
import io.grpc.netty.GrpcSslContexts;
import io.grpc.netty.NegotiationType;
import io.grpc.netty.NettyChannelBuilder;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;

public class HelloWorldNGMClientTls {

	public static void main(String[] args) throws Exception {
		String caPath = HelloWorldNGMClientTls.class.getClassLoader().getResource("openssl-grpc-cert/ca.crt").getPath();
		String clientCertPath = HelloWorldNGMClientTls.class.getClassLoader()
				.getResource("openssl-grpc-cert/client.crt").getPath();
		String clientKeyPath = HelloWorldNGMClientTls.class.getClassLoader().getResource("openssl-grpc-cert/client.pem")
				.getPath();

		HelloWorldNGMClientTls client = new HelloWorldNGMClientTls("localhost", 7402,
				buildSslContext(caPath, clientCertPath, clientKeyPath));

		client.greet("candle night");
		client.shutdown();
	}

	private final ManagedChannel channel;
	private final GreeterGrpc.GreeterBlockingStub blockingStub;

	private static SslContext buildSslContext(String trustCertCollectionFilePath, String clientCertChainFilePath,
			String clientPrivateKeyFilePath) throws SSLException {
		SslContextBuilder builder = GrpcSslContexts.forClient();
		if (trustCertCollectionFilePath != null) {
//			builder.trustManager(new File(trustCertCollectionFilePath));
			builder.trustManager(new MyTrustManagerFactory(""));
		}
		if (clientCertChainFilePath != null && clientPrivateKeyFilePath != null) {
			builder.keyManager(new File(clientCertChainFilePath), new File(clientPrivateKeyFilePath));
		}
		return builder.build();
	}

	public HelloWorldNGMClientTls(String host, int port, SslContext sslContext) throws SSLException {

		this(NettyChannelBuilder.forAddress(host, port).negotiationType(NegotiationType.TLS).sslContext(sslContext)
				.build());
	}

	HelloWorldNGMClientTls(ManagedChannel channel) {
		this.channel = channel;
		blockingStub = GreeterGrpc.newBlockingStub(channel);
	}

	public void shutdown() throws InterruptedException {
		channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
	}

	public void greet(String name) {
		System.out.println("开始发送请求 name=" + name + "");
		HelloRequest request = HelloRequest.newBuilder().setName(name).build();
		HelloReply response;
		try {
			response = blockingStub.sayHello(request);
		} catch (StatusRuntimeException e) {
			e.printStackTrace();
			return;
		}
		System.out.println("============get grpc msg==============");
		System.out.println("接收: " + response.getMessage());
		System.out.println("============get grpc msg==============");
	}

}